#pragma once

#include <iostream>
#include <signal.h>
#include <functional>
#include "Sock.hpp"
#include "log.hpp"

class HttpServer
{
public:
    using func_t = std::function<void (int)>;

    HttpServer(const uint16_t& port, func_t func)
        :_port(port)
        ,_func(func)
    {
        _listensock = sock.Socket();
        sock.Bind(_listensock, _port);
        sock.Listen(_listensock);
    }

    void start()
    {
        signal(SIGCHLD, SIG_IGN);
        while (true)
        {
            std::string client_ip;
            uint16_t client_port;
            int sockfd = sock.Accpet(_listensock, &client_port, &client_ip);
            if (sockfd < 0)
                continue;
            if (fork() == 0)
            {
                close(_listensock);
                _func(sockfd);
                close(sockfd);
                exit(0);
            }
            close(sockfd);
        }
    }

    ~HttpServer()
    {
        if (_listensock >= 0) close(_listensock);
    }
private:
    int _listensock;
    uint16_t _port;
    Sock sock;
    func_t _func;
};
